package com.discordia.asap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

import com.discordia.asap.ImageDownloader.BitmapDownloaderTask;

public class AsapGallery extends Activity {

	ImageAdapter remoteadp;

	private Vector<String> urlsbuff = new Vector<String>();
	private Vector<String> idbuff = new Vector<String>();
	private Vector<String[]> tagbuff = new Vector<String[]>();
	private Vector<String> flagbuff = new Vector<String>();
	
	private static final int SETTINGS_MENU = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mosaic);

		final Gallery gallery = (Gallery) findViewById(R.id.gallery);
		getImgData();
		String[] urls = new String[urlsbuff.size()];
		urlsbuff.copyInto(urls);
		String[] ids = new String[idbuff.size()];
		idbuff.copyInto(ids);
		remoteadp = new ImageAdapter(this, urls, ids);
		gallery.setAdapter(remoteadp);

		gallery.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				String tagtext = "";
				if(tagbuff.size() < 1)
					return;
				for(int j = 0; j < tagbuff.elementAt(position).length; j++){
					String tagid = tagbuff.elementAt(position)[j];
					if(tagid.length() > 0)
						tagtext += AsapActivity.tagItems[Integer.parseInt(tagid)] + " ";
				}
				Toast.makeText(AsapGallery.this, "" + tagtext,
						Toast.LENGTH_SHORT).show();
			}
		});
		
		gallery.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View v,
					int position, long id) {
				Bundle bundle = new Bundle();
				bundle.putString("imgid", Long.toString(id));
				Intent intent = new Intent(AsapGallery.this, AsapImage.class);
				intent.putExtras(bundle);
				startActivity(intent);
				return false;
			}
			
		});
	}
	
	public void showImage(View view){
		final Gallery gallery = (Gallery) findViewById(R.id.gallery);
		long id = gallery.getSelectedItemId();
		Bundle bundle = new Bundle();
		bundle.putString("imgid", Long.toString(id));
		Intent intent = new Intent(AsapGallery.this, AsapImage.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	public void goFirst(View view){
		final Gallery gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setSelection(0);
	}
	
	public void goLast(View view){
		final Gallery gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setSelection(gallery.getAdapter().getCount()-1);	
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.menu_settings:
	        /*LinearLayout setts = (LinearLayout) findViewById(R.id.include_settings);
	        setts.setVisibility(LinearLayout.VISIBLE);*/
	    	showDialog(SETTINGS_MENU);
	        return true;
	    case R.id.menu_refresh:
	    	getImgData();
	    	remoteadp.notifyDataSetChanged();
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	/**
	 * 
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case SETTINGS_MENU: {
			dialog = new Dialog(this, android.R.style.Theme_Translucent);
			dialog.setContentView(R.layout.settings_layout);
			dialog.setTitle("Settings");
			break;
		}
		default:
			dialog = null;
		}
		return dialog;
	}
	
	
	/**
	 * Get images url from the server
	 */
	private void getImgData() {

		try {

			String link = "http://" + AsapActivity.server + AsapActivity.script_folder + "/get_imgs.php";
			DefaultHttpClient hc = new DefaultHttpClient();
			HttpPost postMethod = new HttpPost(link);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			String lastid = "-1";
			if(idbuff.size() > 0)
				lastid = idbuff.lastElement();
			nameValuePairs.add(new BasicNameValuePair("fid", lastid));

			postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			BasicHttpResponse httpResponse;

			httpResponse = (BasicHttpResponse) hc.execute(postMethod);
			HttpEntity responseEntity = httpResponse.getEntity();
			/*
			 * From the php script we receive back a stream of data that has to
			 * be parsed.The string with the information we need starts with the
			 * key FEEDBACK_START and continueswith all the feedback data. Every
			 * information starts with its feedback key and it isseparated from
			 * other informations by a couple of ""TODO: define a better
			 * feedback solution to avoid the use of String.substring()
			 */

			InputStream responseStream = responseEntity.getContent();

			BufferedReader r = new BufferedReader(new InputStreamReader(
					responseStream));
			String line;
			while ((line = r.readLine()) != null) {
				Log.e("Asap", "Message: " + line);
				if (line.contains("FEEDBACK_START")) {
					String feedback[] = line.split("\"\"");
					for (int k = 0; k < feedback.length; k++) {
						if (feedback[k].contains("FEEDBACK_IMG_NAME")){
							urlsbuff.add("http://" + AsapActivity.server
									+ AsapActivity.script_folder + "/images/" + feedback[k].substring(17).replace("\"", "").trim() + ".jpg");
							idbuff.add(feedback[k].substring(17).replace("\"", "").trim());
						}else if(feedback[k].contains("FEEDBACK_IMG_TAG")){
							String[] tagarray = feedback[k].substring(16).replace("\"", "").trim().split(";");
							tagbuff.add(tagarray);
							}
						else if(feedback[k].contains("FEEDBACK_IMG_FLAG")){
							flagbuff.add(feedback[k].substring(17).replace("\"", "").trim());
						}
						
					}
				}

			}
			r.close();

		} catch (IOException ioex) {
			Log.e("Asap", "error: " + ioex.getMessage(), ioex);
		}
	}

}

class ImageAdapter extends BaseAdapter {
	int mGalleryItemBackground;
	private Context mContext;
	private String[] URLS;
	private String[] IDS;
	private final ImageDownloader imageDownloader = new ImageDownloader();

	public ImageAdapter(Activity c, String urls[],String ids[]) {
		mContext = c;
		URLS = urls;
		IDS = ids;
		TypedArray attr = mContext
				.obtainStyledAttributes(R.styleable.HelloGallery);
		mGalleryItemBackground = attr.getResourceId(
				R.styleable.HelloGallery_android_galleryItemBackground, 0);

		attr.recycle();

	}

	public int getCount() {
		return URLS.length;
	}

	public String getItem(int position) {
		return URLS[position];
	}

	public long getItemId(int position) {
		return Long.valueOf(IDS[position]);//.hashCode()
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView = new ImageView(mContext);

		// imageView.setImageResource(imgCollection[position].id);
		// imageView.setImageURI(Uri.parse(AsapGallery.server + "/images/"
		// + imgCollection[position].name));
		imageDownloader.download(URLS[position],IDS[position], (ImageView) imageView);
		imageView.setLayoutParams(new Gallery.LayoutParams(300, 200));
		//imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		// imageView.setBackgroundResource(mGalleryItemBackground);

		return imageView;
	}
}

class DownloadedDrawable extends ColorDrawable {
	private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

	public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
		super(Color.BLACK);
		bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>(
				bitmapDownloaderTask);
	}

	public BitmapDownloaderTask getBitmapDownloaderTask() {
		return bitmapDownloaderTaskReference.get();
	}
}